package top.broncho.lottery.ui.main

import android.app.Application
import androidx.lifecycle.MutableLiveData
import androidx.paging.toLiveData
import kotlinx.coroutines.launch
import org.jetbrains.anko.info
import top.broncho.lottery.api.LotteryApi
import top.broncho.lottery.data.IRepositoryManager
import top.broncho.lottery.data.obtainRetrofitService
import top.broncho.lottery.data.obtainRoomDatabase
import top.broncho.lottery.db.AppDataBase
import top.broncho.lottery.db.LotteryEntity
import top.broncho.lottery.model.lottery.Lottery
import top.broncho.lottery.model.ocr.Prize
import top.broncho.lottery.ui.base.BaseViewModule
import top.broncho.lottery.util.checkPrize
import javax.inject.Inject

class MainViewModule @Inject constructor(
    private val manager: IRepositoryManager,
    app: Application
) : BaseViewModule(app) {
    private val api by lazy { manager.obtainRetrofitService<LotteryApi>() }
    val prizeResult = MutableLiveData<Result<List<Prize>>>()

    val latestLottery = MutableLiveData<Result<Lottery>>()

    init {
        loadLatestLottery()
    }

    private fun loadLatestLottery() = launch {
        if (latestLottery.value == null) {
            try {
                val response = api.queryLatest()
                if (response.error_code == 0) {
                    latestLottery.postValue(Result(response.result))
                } else {
                    latestLottery.postValue(Result(throwable = Throwable(response.reason)))
                }
            } catch (e: Exception) {
                latestLottery.postValue(Result(throwable = e))
            }
        }
    }

    fun parseLottery(lottery: LotteryEntity) = launch {
        try {
            val response = api.query(lottery.lotteryNo)
            info { "response: $response" }
            if (response.error_code != 0) {
                prizeResult.postValue(Result(throwable = Throwable(response.reason)))
                return@launch
            }
            val prizeList = lottery.checkPrize(response.result!!)
            prizeResult.postValue(Result(prizeList))
        } catch (e: Exception) {
            prizeResult.postValue(Result(throwable = e))
        }
    }

    fun getAllLotteries() =
        manager.obtainRoomDatabase<AppDataBase>().lotteryDao().queryLotteries().toLiveData(20)

}